package com.bookstore.service.impl;

import com.bookstore.dto.CartItemDTO;
import com.bookstore.entity.Book;
import com.bookstore.entity.CartItem;
import com.bookstore.entity.User;
import com.bookstore.repository.BookRepository;
import com.bookstore.repository.CartRepository;
import com.bookstore.repository.UserRepository;
import com.bookstore.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartRepository cartRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BookRepository bookRepository;

    @Override
    @Transactional
    public ResponseEntity<?> addToCart(CartItemDTO cartItemDTO) {
        User user = userRepository.findById(cartItemDTO.getUserId())
                .orElseThrow(() -> new RuntimeException("User not found"));

        Book book = bookRepository.findById(cartItemDTO.getBookId())
                .orElseThrow(() -> new RuntimeException("Book not found"));

        if (book.getStock() < cartItemDTO.getQuantity()) {
            return ResponseEntity.badRequest().body("库存不足");
        }

        CartItem cartItem = new CartItem();
        cartItem.setUser(user);
        cartItem.setBook(book);
        cartItem.setQuantity(cartItemDTO.getQuantity());
        cartItem.setCreatedAt(LocalDateTime.now());

        cartRepository.save(cartItem);
        return ResponseEntity.ok("添加成功");
    }

    @Override
    public ResponseEntity<List<CartItemDTO>> getCartItems(Long userId) {
        List<CartItem> cartItems = cartRepository.findByUserId(userId);
        List<CartItemDTO> cartItemDTOs = cartItems.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        return ResponseEntity.ok(cartItemDTOs);
    }

    @Override
    @Transactional
    public ResponseEntity<?> updateCartItem(Long cartId, Integer quantity) {
        return cartRepository.findById(cartId)
                .map(cartItem -> {
                    if (cartItem.getBook().getStock() < quantity) {
                        return ResponseEntity.badRequest().body("库存不足");
                    }
                    cartItem.setQuantity(quantity);
                    cartRepository.save(cartItem);
                    return ResponseEntity.ok("更新成功");
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @Override
    @Transactional
    public ResponseEntity<?> addOrUpdateCart(CartItemDTO cartItemDTO) {
        User user = userRepository.findById(cartItemDTO.getUserId())
                .orElseThrow(() -> new RuntimeException("User not found"));

        Book book = bookRepository.findById(cartItemDTO.getBookId())
                .orElseThrow(() -> new RuntimeException("Book not found"));

        if (book.getStock() < cartItemDTO.getQuantity()) {
            return ResponseEntity.badRequest().body("库存不足");
        }

        // 查找用户是否已有该图书的购物车项
        CartItem existingItem = cartRepository.findByUserIdAndBookId(
                cartItemDTO.getUserId(), cartItemDTO.getBookId());

        if (existingItem != null) {
            // 已存在，更新数量
            int newQuantity = existingItem.getQuantity() + cartItemDTO.getQuantity();
            
            // 再次检查库存是否足够
            if (book.getStock() < newQuantity) {
                return ResponseEntity.badRequest().body("库存不足");
            }
            
            existingItem.setQuantity(newQuantity);
            cartRepository.save(existingItem);
            return ResponseEntity.ok("更新成功");
        } else {
            // 不存在，创建新的购物车项
            CartItem cartItem = new CartItem();
            cartItem.setUser(user);
            cartItem.setBook(book);
            cartItem.setQuantity(cartItemDTO.getQuantity());
            cartItem.setCreatedAt(LocalDateTime.now());

            cartRepository.save(cartItem);
            return ResponseEntity.ok("添加成功");
        }
    }

    @Override
    public ResponseEntity<?> removeFromCart(Long cartId) {
        cartRepository.deleteById(cartId);
        return ResponseEntity.ok("删除成功");
    }

    public ResponseEntity<?> removeByIds(List<Long> ids) {
        cartRepository.deleteAllByIdInBatch(ids);
        return ResponseEntity.ok("删除成功");
    }

    public void clear(Long userId){
        ResponseEntity<List<CartItemDTO>> cartItems = getCartItems(userId);
        List<Long> ids = cartItems.getBody().stream().map(d -> d.getId()).collect(Collectors.toList());
        cartRepository.deleteAllById(ids);
    }

    private CartItemDTO convertToDTO(CartItem cartItem) {
        CartItemDTO dto = new CartItemDTO();
        dto.setId(cartItem.getId());
        dto.setBookId(cartItem.getBook().getId());
        dto.setUserId(cartItem.getUser().getId());
        dto.setQuantity(cartItem.getQuantity());
        dto.setPrice(cartItem.getBook().getPrice());
        dto.setBookTitle(cartItem.getBook().getTitle());
        dto.setBookAuthor(cartItem.getBook().getAuthor());
        dto.setImageUrl(cartItem.getBook().getImageUrl());
        return dto;
    }
}